package com.hwz.gulimaill.thridParty.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.PolicyConditions;
import com.hwz.common.utils.R;
import javafx.scene.input.DataFormat;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: hwz
 * @CreateTime: 2025-06-01
 */


@RestController
public class ossController {

    @Value("${alibaba.cloud.access-key}")
    private String accessId;

    @Value("${alibaba.cloud.secret-key}")
    private String accessKey;

    @Value("${alibaba.cloud.oss.endpoint}")
    private String endpoint;

    @Value("${alibaba.cloud.oss.bucket}")
    private String bucket;

    @Resource
    private OSS ossClient;

    @RequestMapping("/oss/policy")
    public R getPolicy() {
        // 1. 创建OSS客户端

        String dirPre = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = dirPre + "/";


        try {
            // 2. 设置策略过期时间（30分钟后过期）
            long expireTime = 30 * 60 * 1000;
            Date expiration = new Date(System.currentTimeMillis() + expireTime);

            // 3. 设置上传策略
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000); // 文件大小限制1GB
//            policyConds.addConditionItem(PolicyConditions.COND_KEY, "starts-with", "user-dir/"); // 上传目录限制

            // 4. 生成签名
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            // 5. 构建返回结果
            Map<String, String> respMap = new LinkedHashMap<>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir); // 前端上传时指定的目录
            respMap.put("host", "https://" + bucket + "." + endpoint); // OSS访问地址
            respMap.put("expire", String.valueOf(expiration.getTime() / 1000)); // 过期时间戳(秒)
            return R.ok().put("data", respMap);
        } finally {
            ossClient.shutdown();
        }
    }
}